/**
 * 六度-周期性报告生成器 - 前端应用
 * 使用 Vue 3 + Element Plus 构建
 * by: 六度科技 04826d.cn
 */
const { createApp, ref, reactive, onMounted, nextTick, toRefs } = Vue;
const { ElMessage } = ElementPlus;

const App = {
    setup() {
        // --- 响应式数据 ---
        const fullscreenLoading = ref(false);
        const activeMenu = ref('report');
        const activeCollapse = ref([]); // 用于手风琴组件，空数组使所有项默认收起
        const configData = ref({});
        
        // 用于重置的备份
        let originalConfigData = {};
        const newScopeName = ref('');
        const inputVisible = reactive({});
        const inputValue = reactive({});
        
        // --- 新增: 用于编辑功能的数据 ---
        const editingScope = reactive({ oldName: null, newName: null });
        const editingEvent = reactive({ scope: null, index: -1, oldValue: null, newValue: null });

        const fileTree = reactive({
            md: [],
            docx: []
        });
        
        const reportForm = reactive({
            // 'monthly' or 'quarterly'
            type: 'monthly', 
            // For monthly
            monthly: {
                period: '',
                events: []
            },
            // For quarterly
            quarterly: {
                year: '',
                quarter: null,
                month_periods: []
            },
            // For random event generation
            randomEventCount: 5,
            avoidWeekends: true,
            avoidHolidays: true
        });
        
        // 节假日数据缓存
        const holidayData = ref({});
        const holidayDataLoaded = ref(false);
        const availableMonths = ref([]);

        // API不再需要基地址
        // const API_BASE_URL = 'http://127.0.0.1:5000';

        // --- 方法 ---
        
        // 获取节假日数据
        const fetchHolidayData = async () => {
            try {
                console.log('开始获取节假日数据...');
                const response = await axios.get('https://cdn.jsdelivr.net/npm/chinese-days/dist/chinese-days.json', {
                    timeout: 10000 // 10秒超时
                });
                
                // 验证响应数据格式
                if (!response.data || typeof response.data !== 'object') {
                    throw new Error('响应数据格式无效');
                }
                
                // 验证数据结构
                const data = response.data;
                if (!data.holidays || typeof data.holidays !== 'object') {
                    throw new Error('节假日数据格式错误：缺少holidays字段');
                }
                
                holidayData.value = data;
                holidayDataLoaded.value = true;
                console.log('节假日数据加载成功，包含数据：');
                console.log('- 节假日:', Object.keys(data.holidays || {}).length, '条');
                console.log('- 调休工作日:', Object.keys(data.workdays || {}).length, '条');
                console.log('- 其他:', Object.keys(data.inLieuDays || {}).length, '条');
                
            } catch (error) {
                console.warn('节假日数据加载失败，程序将继续运行，仅使用周末判断:', error.message || error);
                
                // 完全禁用节假日功能，只依赖周末判断
                holidayDataLoaded.value = false;
                holidayData.value = {
                    holidays: {},
                    workdays: {},
                    inLieuDays: {}
                };
                
                // 可选：提供一些基础的测试数据（可以注释掉这部分来完全禁用节假日功能）
                /*
                holidayData.value = {
                    holidays: {
                        '2025-01-01': "New Year's Day,元旦,1",
                        '2025-05-01': 'Labour Day,劳动节,1',
                        '2025-05-02': 'Labour Day,劳动节,1',
                        '2025-05-03': 'Labour Day,劳动节,1',
                        '2025-10-01': 'National Day,国庆节,3',
                        '2025-10-02': 'National Day,国庆节,3',
                        '2025-10-03': 'National Day,国庆节,3'
                    },
                    workdays: {
                        '2025-04-27': 'Labour Day,劳动节,2',
                        '2025-09-28': 'National Day,国庆节,3'
                    },
                    inLieuDays: {}
                };
                holidayDataLoaded.value = true;
                console.log('使用备用节假日数据');
                */
            }
        };

        // 判断是否为法定节假日
        const isChineseHoliday = (dateStr) => {
            try {
                if (!holidayDataLoaded.value || !holidayData.value || !dateStr) {
                    return false;
                }
                
                // 安全检查数据结构
                if (!holidayData.value.holidays || typeof holidayData.value.holidays !== 'object') {
                    return false;
                }
                
                // chinese-days 格式: { "holidays": {"YYYY-MM-DD": "Name,中文名,数字"}, "workdays": {...}, "inLieuDays": {...} }
                return Boolean(holidayData.value.holidays[dateStr]);
            } catch (error) {
                console.warn('检查节假日时出错:', error);
                return false;
            }
        };

        // 判断是否为调休工作日  
        const isAdjustmentWorkday = (dateStr) => {
            try {
                if (!holidayDataLoaded.value || !holidayData.value || !dateStr) {
                    return false;
                }
                
                // 安全检查数据结构
                if (!holidayData.value.workdays || typeof holidayData.value.workdays !== 'object') {
                    return false;
                }
                
                return Boolean(holidayData.value.workdays[dateStr]);
            } catch (error) {
                console.warn('检查调休工作日时出错:', error);
                return false;
            }
        };

        // 获取节假日名称
        const getHolidayName = (dateStr) => {
            try {
                if (!holidayDataLoaded.value || !holidayData.value || !dateStr) {
                    return '';
                }
                
                // 检查节假日
                if (holidayData.value.holidays && holidayData.value.holidays[dateStr]) {
                    const holiday = holidayData.value.holidays[dateStr];
                    if (typeof holiday === 'string') {
                        // 格式: "Name,中文名,数字" -> 提取中文名
                        const parts = holiday.split(',');
                        return parts.length > 1 ? parts[1] : parts[0];
                    }
                    return holiday.toString();
                }
                
                // 检查调休工作日
                if (holidayData.value.workdays && holidayData.value.workdays[dateStr]) {
                    const workday = holidayData.value.workdays[dateStr];
                    if (typeof workday === 'string') {
                        // 格式: "Name,中文名,数字" -> 提取中文名，并加上"调休"后缀
                        const parts = workday.split(',');
                        const name = parts.length > 1 ? parts[1] : parts[0];
                        return name + '调休';
                    }
                    return workday.toString() + '调休';
                }
                
                return '';
            } catch (error) {
                console.warn('获取节假日名称时出错:', error);
                return '';
            }
        };

        // 获取可用的类型选项（工作范围）
        const getAvailableTypes = () => {
            if (!configData.value || !configData.value.work_scope) {
                return [];
            }
            return Object.keys(configData.value.work_scope);
        };

        // 获取指定类型的可用描述选项
        const getAvailableDescriptions = (type) => {
            if (!configData.value || !configData.value.work_scope || !type || !configData.value.work_scope[type]) {
                return [];
            }
            
            const scopeData = configData.value.work_scope[type];
            
            // 兼容新旧格式
            if (Array.isArray(scopeData)) {
                // 旧格式：直接返回字符串数组
                return scopeData;
            } else if (scopeData && typeof scopeData === 'object' && scopeData.items) {
                // 新格式：返回所有项目的name（无论是否开启随机）
                return scopeData.items.map(item => item.name || item);
            }
            
            return [];
        };

        // 获取事件项数组（兼容新旧格式）
        const getEventItems = (events) => {
            if (Array.isArray(events)) {
                // 旧格式：直接是字符串数组
                return events;
            } else if (events && typeof events === 'object' && events.items) {
                // 新格式：包含items数组
                return events.items;
            }
            return [];
        };

        // 获取事件名称（兼容新旧格式）
        const getEventName = (event) => {
            if (typeof event === 'string') {
                // 旧格式：直接是字符串
                return event;
            } else if (event && typeof event === 'object' && event.name) {
                // 新格式：包含name字段
                return event.name;
            }
            return '';
        };

        // 获取工作范围的随机状态
        const getScopeRandomState = (scope) => {
            if (!configData.value || !configData.value.work_scope || !configData.value.work_scope[scope]) {
                return false;
            }
            const scopeData = configData.value.work_scope[scope];
            if (Array.isArray(scopeData)) {
                // 旧格式：默认为true
                return true;
            } else if (scopeData && typeof scopeData === 'object') {
                // 新格式：返回random字段
                return scopeData.random !== false; // 默认为true
            }
            return false;
        };

        // 获取事件的随机状态
        const getEventRandomState = (event) => {
            if (typeof event === 'string') {
                // 旧格式：默认为true
                return true;
            } else if (event && typeof event === 'object') {
                // 新格式：返回random字段
                return event.random !== false; // 默认为true
            }
            return false;
        };

        // 切换工作范围的随机状态
        const toggleScopeRandom = (scope) => {
            if (!configData.value.work_scope[scope]) return;
            
            const scopeData = configData.value.work_scope[scope];
            if (Array.isArray(scopeData)) {
                // 旧格式转新格式
                configData.value.work_scope[scope] = {
                    random: false, // 切换后的状态
                    items: scopeData.map(item => ({ name: item, random: true }))
                };
            } else if (scopeData && typeof scopeData === 'object') {
                // 新格式：切换random状态
                scopeData.random = !scopeData.random;
            }
        };

        // 切换事件的随机状态
        const toggleEventRandom = (scope, index) => {
            if (!configData.value.work_scope[scope]) return;
            
            const scopeData = configData.value.work_scope[scope];
            let items = getEventItems(scopeData);
            
            if (index >= 0 && index < items.length) {
                let item = items[index];
                if (typeof item === 'string') {
                    // 旧格式转新格式
                    items[index] = { name: item, random: false }; // 切换后的状态
                    
                    // 如果整个scope还是旧格式，也需要转换
                    if (Array.isArray(scopeData)) {
                        configData.value.work_scope[scope] = {
                            random: true,
                            items: items.map((it, idx) => 
                                idx === index ? items[index] : 
                                (typeof it === 'string' ? { name: it, random: true } : it)
                            )
                        };
                    }
                } else if (item && typeof item === 'object') {
                    // 新格式：切换random状态
                    item.random = !item.random;
                }
            }
        };

        // 导航切换
        const handleMenuSelect = (index) => {
            activeMenu.value = index;
            // 切换时可以根据需要加载数据
            if (index === 'files') {
                fetchFiles();
            } else if (index === 'config') {
                fetchConfig();
            }
        };

        // 获取配置
        const fetchConfig = async () => {
            fullscreenLoading.value = true;
            try {
                const response = await axios.get('/api/config');
                console.log('原始配置数据:', response.data);
                
                // 确保work_scope存在
                if (!response.data.work_scope) {
                    response.data.work_scope = {};
                }
                
                // 创建一个全新的响应式对象
                const newConfigData = {
                    engineer_name: response.data.engineer_name || '',
                    client_name: response.data.client_name || '',
                    contractor_name: response.data.contractor_name || '',
                    work_scope: {}
                };
                
                // 复制工作范围数据（兼容新旧格式）
                if (response.data.work_scope) {
                    Object.keys(response.data.work_scope).forEach(scope => {
                        const scopeData = response.data.work_scope[scope];
                        
                        if (Array.isArray(scopeData)) {
                            // 旧格式：直接复制数组
                            newConfigData.work_scope[scope] = [...scopeData];
                        } else if (scopeData && typeof scopeData === 'object') {
                            // 新格式：保持对象结构
                            newConfigData.work_scope[scope] = {
                                random: scopeData.random !== false, // 确保有默认值
                                items: scopeData.items ? [...scopeData.items] : []
                            };
                        }
                        
                        // 初始化输入框可见性数据
                        inputVisible[scope] = false;
                        inputValue[scope] = '';
                    });
                }
                
                // 赋值给配置数据
                configData.value = newConfigData;
                
                // 深拷贝一份原始数据用于重置
                originalConfigData = JSON.parse(JSON.stringify(newConfigData));
                
                console.log('处理后的配置数据:', configData.value);
                console.log('工作范围数据:', configData.value.work_scope);
                
                // 不自动展开任何工作范围，保持默认收起状态
                
            } catch (error) {
                console.error('配置加载失败', error);
                ElMessage.error('配置加载失败，请检查后端服务是否开启。');
            } finally {
                fullscreenLoading.value = false;
            }
        };

        // 保存配置
        const saveConfig = async () => {
            fullscreenLoading.value = true;
            try {
                await axios.post('/api/config', configData.value);
                ElMessage.success('配置保存成功！');
                // 更新备份数据
                originalConfigData = JSON.parse(JSON.stringify(configData.value));
            } catch (error) {
                console.error('配置保存失败', error);
                ElMessage.error('配置保存失败！');
            } finally {
                fullscreenLoading.value = false;
            }
        };

        // 重置配置
        const resetConfig = () => {
            configData.value = JSON.parse(JSON.stringify(originalConfigData));
            ElMessage.info('配置已重置为上次保存的状态。');
        };

        // --- 工作范围与事件管理方法 ---
        const addScope = () => {
            if (!configData.value) {
                configData.value = reactive({
                    work_scope: {}
                });
            }
            
            if (!configData.value.work_scope) {
                configData.value.work_scope = {};
            }
            
            if (newScopeName.value && !configData.value.work_scope[newScopeName.value]) {
                // 创建新对象，以确保Vue能够检测到更改
                const updatedWorkScope = { ...configData.value.work_scope };
                updatedWorkScope[newScopeName.value] = {
                    random: true,  // 默认开启随机
                    items: []
                };
                configData.value.work_scope = updatedWorkScope;
                
                // 添加到输入框状态管理
                inputVisible[newScopeName.value] = false;
                inputValue[newScopeName.value] = '';
                
                // 添加成功后，自动展开新的范围
                activeCollapse.value = newScopeName.value;
                newScopeName.value = '';
                ElMessage.success('工作范围添加成功！');
                console.log('工作范围添加成功', configData.value.work_scope);
            } else {
                ElMessage.warning('工作范围名称不能为空或已存在！');
            }
        };

        const deleteScope = (scopeToDelete) => {
            if (scopeToDelete) {
                // 创建新对象，以确保Vue能够检测到更改
                const updatedWorkScope = { ...configData.value.work_scope };
                delete updatedWorkScope[scopeToDelete];
                configData.value.work_scope = updatedWorkScope;
                
                ElMessage.success(`工作范围 "${scopeToDelete}" 已删除。`);
                console.log('工作范围删除成功', configData.value.work_scope);
            } else {
                ElMessage.warning('未能确定要删除的工作范围。');
            }
        };

        const handleConfigEventDelete = (scope, index) => {
            const scopeData = configData.value.work_scope[scope];
            const items = getEventItems(scopeData);
            
            if (items && index >= 0 && index < items.length) {
                const updatedWorkScope = { ...configData.value.work_scope };
                
                if (Array.isArray(scopeData)) {
                    // 旧格式：直接删除数组元素
                    const updatedEvents = [...scopeData];
                    updatedEvents.splice(index, 1);
                    updatedWorkScope[scope] = updatedEvents;
                } else if (scopeData && typeof scopeData === 'object' && scopeData.items) {
                    // 新格式：删除items中的元素
                    const updatedItems = [...scopeData.items];
                    updatedItems.splice(index, 1);
                    updatedWorkScope[scope] = {
                        ...scopeData,
                        items: updatedItems
                    };
                }
                
                configData.value.work_scope = updatedWorkScope;
                console.log('事件删除成功', scope, updatedWorkScope[scope]);
            }
        };

        const showInput = (scope) => {
            inputVisible[scope] = true;
            // nextTick is needed to wait for the DOM to update
            // however, since we are not in a component context, we use a simple timeout
            setTimeout(() => {
                // This part is tricky without component refs, we might need to rely on vanilla JS if this doesn't work
                // For now, we just make it visible
            }, 0);
        };

        const handleInputConfirm = (scope) => {
            if (inputValue[scope]) {
                const scopeData = configData.value.work_scope[scope];
                
                // 兼容新旧格式
                if (Array.isArray(scopeData)) {
                    // 旧格式：检查是否已存在
                    if (!scopeData.includes(inputValue[scope])) {
                        // 转换为新格式并添加
                        const updatedWorkScope = { ...configData.value.work_scope };
                        updatedWorkScope[scope] = {
                            random: true,  // 默认开启随机
                            items: [
                                ...scopeData.map(item => ({ name: item, random: true })),
                                { name: inputValue[scope], random: true }  // 新项目默认开启随机
                            ]
                        };
                        configData.value.work_scope = updatedWorkScope;
                        console.log('事件添加成功（格式已升级）', scope, updatedWorkScope[scope]);
                    }
                } else if (scopeData && typeof scopeData === 'object' && scopeData.items) {
                    // 新格式：检查items中是否已存在
                    const existingNames = scopeData.items.map(item => item.name);
                    if (!existingNames.includes(inputValue[scope])) {
                        const updatedWorkScope = { ...configData.value.work_scope };
                        updatedWorkScope[scope] = {
                            ...scopeData,
                            items: [...scopeData.items, { name: inputValue[scope], random: true }]  // 新项目默认开启随机
                        };
                        configData.value.work_scope = updatedWorkScope;
                        console.log('事件添加成功', scope, updatedWorkScope[scope]);
                    }
                }
            }
            inputVisible[scope] = false;
            inputValue[scope] = '';
        };

        // 获取文件列表
        const fetchFiles = async () => {
            fullscreenLoading.value = true;
            try {
                const response = await axios.get('/api/list_files');
                if (response.data.status === 200) {
                    // 后端返回的数据需要转换为el-tree需要的格式
                    fileTree.md = transformFileTree(response.data.files.md);
                    fileTree.docx = transformFileTree(response.data.files.docx);
                    console.log('文件列表加载并转换成功', fileTree);
                } else {
                    ElMessage.error(response.data.message);
                }
            } catch (error) {
                console.error('文件列表加载失败', error);
                ElMessage.error('文件列表加载失败，请检查后端服务是否开启。');
            } finally {
                fullscreenLoading.value = false;
            }
        };

        // 转换后端文件结构为el-tree所需格式
        const transformFileTree = (data) => {
            if (!data) return [];
            return Object.keys(data).map(year => {
                const yearNode = {
                    label: `${year}年`,
                    children: []
                };
                const reportTypes = data[year];
                yearNode.children = Object.keys(reportTypes).map(type => {
                    const typeNode = {
                        label: type,
                        children: []
                    };
                    const files = reportTypes[type];
                    if (Array.isArray(files)) {
                        typeNode.children = files.map(file => ({
                            label: file,
                            icon: 'el-icon-document'
                        }));
                    }
                    return typeNode;
                });
                return yearNode;
            });
        };

        // --- 报告生成方法 ---
        const generateRandomEventsLocally = (count, period, avoidWeekends, avoidHolidays = true) => {
            const work_scope = configData.value.work_scope || {};

            const [year, month] = period.split('-').map(Number);
            const startDate = new Date(year, month - 1, 1);
            const endDate = new Date(year, month, 0); // Day 0 of next month is last day of current month
            const totalDays = endDate.getDate() - startDate.getDate();

            const all_events = [];
            for (const scope in work_scope) {
                if (work_scope.hasOwnProperty(scope)) {
                    const scopeData = work_scope[scope];
                    
                    // 兼容新旧格式
                    if (Array.isArray(scopeData)) {
                        // 旧格式：直接是字符串数组
                        scopeData.forEach(desc => {
                            all_events.push({ type: scope, description: desc });
                        });
                    } else if (scopeData && typeof scopeData === 'object') {
                        // 新格式：包含random和items字段
                        if (scopeData.random && scopeData.items) {
                            scopeData.items.forEach(item => {
                                // 只有当工作范围和具体事件都开启随机时才参与随机生成
                                if (item.random) {
                                    all_events.push({ type: scope, description: item.name });
                                }
                            });
                        }
                    }
                }
            }

            if (all_events.length === 0) {
                return [];
            }

            // Shuffle and pick
            const shuffled = all_events.sort(() => 0.5 - Math.random());
            const selectedEvents = shuffled.slice(0, Math.min(count, all_events.length));
            
            const generated_events = selectedEvents.map(event => {
                let eventDate;
                let attempts = 0;
                
                while (attempts < 100) {
                    const randomDayOffset = Math.floor(Math.random() * (totalDays + 1));
                    eventDate = new Date(startDate);
                    eventDate.setDate(startDate.getDate() + randomDayOffset);
                    
                    const y = eventDate.getFullYear();
                    const m = String(eventDate.getMonth() + 1).padStart(2, '0');
                    const d = String(eventDate.getDate()).padStart(2, '0');
                    const dateStr = `${y}-${m}-${d}`;
                    
                    // 检查是否避开周末
                    if (avoidWeekends) {
                        const day = eventDate.getDay();
                        if (day === 0 || day === 6) { // 0 = Sunday, 6 = Saturday
                            attempts++;
                            continue;
                        }
                    }
                    
                    // 检查是否避开法定节假日
                    if (avoidHolidays && isChineseHoliday(dateStr)) {
                        attempts++;
                        continue;
                    }
                    
                    // 调休工作日应该被认为是工作日，所以不避开
                    break;
                }
                
                // 如果尝试了100次还没找到合适的日期，使用最后一次生成的日期
                if (attempts >= 100) {
                    console.warn('在生成随机事件时达到最大尝试次数，可能包含节假日或周末');
                }
                
                const y = eventDate.getFullYear();
                const m = String(eventDate.getMonth() + 1).padStart(2, '0');
                const d = String(eventDate.getDate()).padStart(2, '0');

                return {
                    ...event,
                    date: `${y}-${m}-${d}` // YYYY-MM-DD
                };
            });

            // Sort by date
            generated_events.sort((a, b) => new Date(a.date) - new Date(b.date));

            return generated_events;
        };

        const handleGenerateRandomEvents = async () => {
            if (!reportForm.monthly.period) {
                ElMessage.warning('请先选择报告月份！');
                return;
            }
            fullscreenLoading.value = true;
            try {
                // Call local function instead of API
                const events = generateRandomEventsLocally(reportForm.randomEventCount, reportForm.monthly.period, reportForm.avoidWeekends, reportForm.avoidHolidays);
                reportForm.monthly.events = events;
                ElMessage.success('随机事件已生成并填充！');
            } catch (error) {
                ElMessage.error('生成随机事件失败！');
                console.error(error);
            } finally {
                fullscreenLoading.value = false;
            }
        };
        
        const handleReportEventDelete = (index) => {
            reportForm.monthly.events.splice(index, 1);
        };

        const handleAddReportEvent = () => {
            if (!reportForm.monthly.period) {
                ElMessage.warning('请先选择报告月份！');
                return;
            }

            reportForm.monthly.events.push({
                date: '', // 留空让用户自己选择日期
                type: '',
                description: ''
            });
        };

        const handleYearOrQuarterChange = () => {
            const year = reportForm.quarterly.year;
            const quarter = reportForm.quarterly.quarter;

            if(!year || !quarter) {
                availableMonths.value = [];
                reportForm.quarterly.month_periods = [];
                return;
            }

            const startMonth = (quarter - 1) * 3 + 1;
            
            const months = [];
            for (let i = 0; i < 3; i++) {
                const month = startMonth + i;
                months.push({
                    label: `${year}年${month}月`,
                    value: `${year}-${month}`
                });
            }
            availableMonths.value = months;
            // 默认全选
            reportForm.quarterly.month_periods = months.map(m => m.value);
        };

        const generateReport = async () => {
            fullscreenLoading.value = true;
            let payload = {};
            
            if (reportForm.type === 'monthly') {
                if (!reportForm.monthly.period) {
                    ElMessage.warning('请选择报告月份！');
                    fullscreenLoading.value = false;
                    return;
                }
                payload = {
                    type: 'monthly',
                    period: reportForm.monthly.period,
                    events: reportForm.monthly.events
                };
            } else { // quarterly
                 if (!reportForm.quarterly.year || !reportForm.quarterly.quarter) {
                    ElMessage.warning('请选择完整的报告季度！');
                    fullscreenLoading.value = false;
                    return;
                }
                payload = {
                    type: 'quarterly',
                    period: `${reportForm.quarterly.year}-Q${reportForm.quarterly.quarter}`,
                    month_periods: reportForm.quarterly.month_periods
                };
            }

            try {
                const response = await axios.post('/api/generate_report', payload);
                if (response.data.status === 200) {
                    ElMessage.success('报告生成成功！请到文件清单页面查看。');
                    if (response.data.warnings) {
                        ElMessage.warning({
                            message: `报告生成完毕，但有以下警告: ${response.data.warnings.join(', ')}`,
                            duration: 5000
                        });
                    }
                    // 刷新文件列表
                    fetchFiles();
                } else {
                    ElMessage.error(`报告生成失败: ${response.data.message}`);
                }
            } catch (error) {
                ElMessage.error('请求报告生成失败！');
                console.error(error);
            } finally {
                fullscreenLoading.value = false;
            }
        };

        // --- 新增: 编辑功能的处理函数 ---
        const startEditScope = (scope) => {
            // 检查是否已在编辑状态
            if (editingScope.oldName === scope) {
                // 如果是，则退出编辑状态
                editingScope.oldName = '';
                editingScope.newName = '';
                return;
            }
            
            editingScope.oldName = scope;
            editingScope.newName = scope;
            
            // 等待DOM更新后聚焦输入框
            nextTick(() => {
                if (document.querySelector('.collapse-title input')) {
                    document.querySelector('.collapse-title input').focus();
                }
            });
        };

        const finishEditScope = () => {
            const { oldName, newName } = editingScope;
            if (newName && oldName !== newName && !configData.value.work_scope[newName]) {
                // 为了确保Vue的响应性，我们创建一个新对象
                const newWorkScope = {};
                for (const key in configData.value.work_scope) {
                    if (key === oldName) {
                        newWorkScope[newName] = configData.value.work_scope[oldName];
                    } else {
                        newWorkScope[key] = configData.value.work_scope[key];
                    }
                }
                configData.value.work_scope = newWorkScope;
                
                // 如果当前折叠项是正在编辑的项，则更新它
                if (activeCollapse.value === oldName) {
                    activeCollapse.value = newName;
                }
            } else if (newName && oldName !== newName) {
                ElMessage.warning(`工作范围 "${newName}" 已存在！`);
            }
            // 重置编辑状态
            editingScope.oldName = null;
            editingScope.newName = null;
        };

        const startEditEvent = (scope, index) => {
            // 检查是否已在编辑状态
            if (editingEvent.scope === scope && editingEvent.index === index) {
                // 如果是，则退出编辑状态
                editingEvent.scope = null;
                editingEvent.index = null;
                editingEvent.oldValue = '';
                editingEvent.newValue = '';
                return;
            }
            
            const event = configData.value.work_scope[scope][index];
            editingEvent.scope = scope;
            editingEvent.index = index;
            editingEvent.oldValue = event;
            editingEvent.newValue = event;
            
            // 等待DOM更新后聚焦输入框
            nextTick(() => {
                if (document.querySelector('.event-edit-input input')) {
                    document.querySelector('.event-edit-input input').focus();
                }
            });
        };

        const finishEditEvent = () => {
            const { scope, index, newValue, oldValue } = editingEvent;
            if (newValue && newValue !== oldValue) {
                // 检查新值是否已存在（可选）
                if (configData.value.work_scope[scope].includes(newValue)) {
                    ElMessage.warning(`事件 "${newValue}" 在当前范围已存在。`);
                } else {
                    // 创建新数组并更新数据
                    const updatedEvents = [...configData.value.work_scope[scope]];
                    updatedEvents[index] = newValue;
                    
                    // 更新工作范围对象
                    const updatedWorkScope = { ...configData.value.work_scope };
                    updatedWorkScope[scope] = updatedEvents;
                    configData.value.work_scope = updatedWorkScope;
                    
                    console.log('事件编辑成功', scope, updatedWorkScope[scope]);
                }
            }
            editingEvent.scope = null;
            editingEvent.index = -1;
            editingEvent.oldValue = null;
            editingEvent.newValue = null;
        };

        const disabledDatesForMonthlyReport = (time) => {
            if (!reportForm.monthly.period) {
                return true;
            }
            const [year, month] = reportForm.monthly.period.split('-').map(Number);
            const selectedMonthFirstDay = new Date(year, month - 1, 1);
            // In JS Date, month is 0-indexed.
            const nextMonthFirstDay = new Date(year, month, 1);
            return time.getTime() < selectedMonthFirstDay.getTime() || time.getTime() >= nextMonthFirstDay.getTime();
        };

        const dateCellClassName = (cellDate) => {
            if (!cellDate) {
                return '';
            }
            
            // 将 Date 对象转换为 YYYY-MM-DD 格式
            const y = cellDate.getFullYear();
            const m = String(cellDate.getMonth() + 1).padStart(2, '0');
            const d = String(cellDate.getDate()).padStart(2, '0');
            const dateStr = `${y}-${m}-${d}`;
            
            // 优先级：节假日 > 调休工作日 > 周末
            if (isChineseHoliday(dateStr)) {
                console.log(`节假日检测: ${dateStr} 是节假日`);
                return 'is-holiday';
            }
            
            if (isAdjustmentWorkday(dateStr)) {
                console.log(`调休检测: ${dateStr} 是调休工作日`);
                return 'is-adjustment-workday';
            }
            
            // getDay() returns 0 for Sunday, 6 for Saturday
            if ([0, 6].includes(cellDate.getDay())) {
                return 'is-weekend';
            }
            
            return '';
        };

        // 获取日期选择器的默认显示日期（跳转到选择的年月）
        const getDefaultDateForPicker = () => {
            if (reportForm.monthly.period) {
                // 从YYYY-MM格式创建该月的第一天
                const [year, month] = reportForm.monthly.period.split('-');
                return new Date(parseInt(year), parseInt(month) - 1, 1);
            }
            // 如果没有选择月份，返回当前日期
            return new Date();
        };

        // --- 生命周期钩子 ---
        onMounted(async () => {
            // 并行加载数据，确保即使某些失败，其他功能也能正常工作
            try {
                await Promise.allSettled([
                    fetchHolidayData().catch(err => console.warn('节假日数据加载失败，程序继续运行:', err)),
                    fetchConfig().catch(err => console.warn('配置数据加载失败:', err)),
                    fetchFiles().catch(err => console.warn('文件列表加载失败:', err))
                ]);
                console.log('应用初始化完成');
            } catch (error) {
                console.error('应用初始化时发生意外错误:', error);
                // 即使发生错误，应用仍然应该可用
            }
        });

        // --- 返回给模板的数据和方法 ---
        return {
            fullscreenLoading,
            activeMenu,
            activeCollapse,
            configData,
            newScopeName,
            inputVisible,
            inputValue,
            fileTree,
            reportForm,
            availableMonths,
            handleMenuSelect,
            fetchConfig,
            saveConfig,
            resetConfig,
            addScope,
            deleteScope,
            handleConfigEventDelete,
            showInput,
            handleInputConfirm,
            fetchFiles,
            handleGenerateRandomEvents,
            handleReportEventDelete,
            handleAddReportEvent,
            handleYearOrQuarterChange,
            generateReport,
            editingScope,
            editingEvent,
            startEditScope,
            finishEditScope,
            startEditEvent,
            finishEditEvent,
            disabledDatesForMonthlyReport,
            dateCellClassName,
            fetchHolidayData,
            isChineseHoliday,
            isAdjustmentWorkday,
            getHolidayName,
            holidayDataLoaded,
            getAvailableTypes,
            getAvailableDescriptions,
            getEventItems,
            getEventName,
            getScopeRandomState,
            getEventRandomState,
            toggleScopeRandom,
            toggleEventRandom,
            getDefaultDateForPicker
        };
    }
};

const app = createApp(App);

// 设置Element Plus的语言为中文
app.use(ElementPlus, { locale: ElementPlusLocaleZhCn });

app.mount('#app'); 